package leetcode;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 设有3个线程，让这3个线程顺序交替打印abc 10 次
 * @date 2020/3/10 22:44
 */
public class Code1114_PrintABC{



    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore1 = new Semaphore(1);
        Semaphore semaphore2 = new Semaphore(0);
        Semaphore semaphore3 = new Semaphore(0);
        AtomicInteger count = new AtomicInteger(0);
        int maxcount = 30;
        new Thread(()->{
            while (count.get() < maxcount){
                try {
                    semaphore1.acquire();
                    if(count.get() < maxcount){
                        System.out.print("a"+count.get());
                        count.getAndIncrement();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore2.release();
                }
            }
        }).start();

        new Thread(()->{
            while (count.get() < maxcount){
                try {
                    semaphore2.acquire();
                    if(count.get() < maxcount){
                        System.out.print("b"+count.get());
                        count.getAndIncrement();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore3.release();
                }
            }
        }).start();

        new Thread(()->{
            while (count.get() < maxcount){
                try {
                    semaphore3.acquire();
                    if(count.get() < maxcount){
                        System.out.println("c"+count.get());
                        count.getAndIncrement();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore1.release();
                }
            }
        }).start();

    }



}
